package WebTools::Train;
use strict;
use warnings;
use base qw/WebCore/;
use utf8;

use Data::Dumper;
use WebModule::Train;
use WebModule::Train::Manager;
use WebModule::TrainStation;
use WebModule::TrainStation::Manager;
use WebModule::Station;
use WebModule::Station::Manager;

use Data::FormValidator::Constraints qw(ip_address);

use Encode;


#定义每页显示得记录数据
my $pre_page_number = 18;

#显示默认的或者时刻信息查询列表
sub home:Default {
    my $this = shift;
    $this->set_tt_var('customer_title', '火车时刻表 - 5anet.com');
    return $this->process_template('train.tt2');
}

#需要使用表单验证
#根据车次查询
sub findbynumber:Path('findbynumber') {#{{{

    my $this = shift;

    #验证表单
    my $check_form_result = $this->check_rm('_train_number_form_validate',
        '_train_number_form_profile')
        || return $this->check_rm_error_page;


    #验证通过后，取得验证后得结果
    my $train_number = uc $check_form_result->valid('train_number');

    my $page = $this->query->param('page');

    if ( !$page ) {
        $page = 1;
    }

    #根据train_number进行查询
    my $trains = WebModule::Train::Manager->get_train(
        query=>[
        train_number=>{ like=>[$train_number.'%', '%'.$train_number] },
        ],
        sort_by=>'id desc',
        per_page=>$pre_page_number,
        page=>$page
    );

    $this->set_tt_var('customer_title', '按车次:'.$train_number.'查询火车时刻表查询结果 - 5anet.com');
    $this->set_tt_var('train_number', $train_number);
    $this->set_tt_var('pre_page', $page-1);
    $this->set_tt_var('next_page', $page+1);
    $this->set_tt_var('trains', $trains);
    return $this->process_template('trainresult.tt2');

}#}}}


#根据经过的站点来查询
sub findbystation:Path('findbystation') {
    my $this = shift;

    my $station = $this->query->param('station');
    my $page = $this->query->param('page');
    
    if ( !$page ) {
        $page = 1;
    }

    my $train_stations = WebModule::TrainStation::Manager->get_train_station(
        with_objects=>['station'],
        query=>[
            'station.station'=>{ like => $station.'%' },
        ],
        sort_by=>'t1.id asc',
        per_page=>$pre_page_number,
        page=>$page,
    );

    $this->set_tt_var('customer_title', '按站点'.decode('utf-8', $station).
            '查询火车时刻表查询结果 - 5anet.com');
    $this->set_tt_var('pre_page', $page-1);
    $this->set_tt_var('next_page', $page+1);
    $this->set_tt_var('trains', $train_stations);
    $this->set_tt_var('station', decode('utf-8', $station));

    return $this->process_template('trainresult4.tt2');


}


#根据起始站和终点站来查询
sub findbystations:Path('findbystations') {#{{{
    my $this = shift;

    my $begin_station = $this->query->param('bstation');
    my $end_station = $this->query->param('estation');
    my $page = $this->query->param('page');

    if ( !$page ) {
        $page = 1;
    }

    #很复杂的查询还是不得不使用
    #DBI接口
    my $stations = WebModule::Station::Manager->get_stations(
        query=>[
        station=>{ like=>$begin_station.'%' },
        ],
        sort_by=>'id asc',
    );

    my @b_ids;
    foreach my $station ( @$stations ) {
        $b_ids[++$#b_ids] = $station->id;
    }


    $stations = WebModule::Station::Manager->get_stations(
        query=>[
        station=>{ like=>$end_station.'%' },
        ],
        sort_by=>'id asc',
    );

    my @e_ids;
    foreach my $station ( @$stations ) {
        $e_ids[++$#e_ids] = $station->id;
    }

    #开始生成查询语句
    if ( !scalar(@b_ids) || !scalar(@e_ids) ) {
        return $this->home;
    }

    my $a_where = '(';
    
    for(my $i=0; $i<scalar @b_ids; $i++) {
        $a_where .= ' a.station_id= '.$b_ids[$i];

        if ( $i < (scalar @b_ids) - 1 ) {
            $a_where .= ' or ';
        }
    }
    $a_where .= ')';

    my $b_where = '(';
    
    for(my $i=0; $i<scalar @e_ids; $i++) {
        $b_where .= ' b.station_id= '.$e_ids[$i];

        if ( $i < (scalar @e_ids) - 1 ) {
            $b_where .= ' or ';
        } 
    }
    $b_where .= ') ';



    my $sql = 'select count(a.id) as num from train_station as a, train_station as b '.
        ' where a.train_id = b.train_id  and '.$a_where.' and '.$b_where;


    my $stmt = $this->dbh->prepare($sql);
    $stmt->execute;
    my $rows = $stmt->fetchrow_hashref;
    my $total_number = $rows->{'num'};
    my $total_page = int($total_number / $pre_page_number + 0.99 );

    if ( $total_page>0 && $page > $total_page ) {
        $page = $total_page;
    }

    my $offset = (  $page - 1 ) * $pre_page_number;

    $sql = "select a.id, a.train_id, a.station_id, a.arrive_time, a.start_out_time, 
        a.cost_time, a.course from train_station as a, train_station as b where 
        a.train_id = b.train_id and $a_where and $b_where limit $pre_page_number offset 
        $offset 
        ";

    my $train_stations = WebModule::TrainStation::Manager->get_objects_from_sql(
        sql=>$sql,
    );


    $this->set_tt_var('customer_title', '按起始站终点站查询火车时刻表查询结果 - 5anet.com');
    $this->set_tt_var('pre_page', $page-1);
    $this->set_tt_var('next_page', $page+1);
    $this->set_tt_var('train_stations', $train_stations);
    $this->set_tt_var('begin_station', decode('utf-8', $begin_station));
    $this->set_tt_var('end_station', decode('utf-8', $end_station));
    return $this->process_template('trainresult3.tt2');

}#}}}


#显示车次的详细信息
sub detail:Regex('detail/(\d+)') {#{{{
    my $this = shift;
    my ($train_id) = $this->action_args;

    my $train = WebModule::Train->new(id=>$train_id);
    $train->load(speculative=>1);


    my $train_stations = WebModule::TrainStation::Manager->get_train_station(
        query=>[
        train_id=>$train->id,
        ],
        sort_by=>'id asc',
    );

    $this->set_tt_var('customer_title', '查看车次:'.$train->train_number.'详细 - 5anet.com');
    $this->set_tt_var('train', $train);
    $this->set_tt_var('train_stations', $train_stations);
    return $this->process_template('traindetail.tt2');

}#}}}

#根据站点ID查询经过的列车
sub findbystationid:Regex('findbystationid/(\d+)/(\d+)') {#{{{
    my $this = shift;
    my ($station_id, $page) = $this->action_args();

    if ( !$page ) {
        $page = 1;
    }

    my $train_stations = WebModule::TrainStation::Manager->get_train_station(
        query=>[
                station_id=>$station_id,
            ],
        sort_by=>'id asc',
        per_page=>$pre_page_number,
        page=>$page,
    );

    $this->set_tt_var('customer_title', '按站点ID:'.$station_id.'查询火车时刻表查询结果 - 5anet.com');
    $this->set_tt_var('train_number', $station_id);
    $this->set_tt_var('pre_page', $page-1);
    $this->set_tt_var('next_page', $page+1);
    $this->set_tt_var('trains', $train_stations);
    $this->set_tt_var('station_id', $station_id);

    return $this->process_template('trainresult2.tt2');

}#}}}


#验证车次的表单
sub _train_number_form_validate {#{{{

    my $this = shift;
    my $errs = shift;
    
    foreach my $key ( keys %$errs ) {
        $this->set_tt_var($key, $errs->{$key});
    }

    return $this->home;
}#}}}

#车次表单得验证profile
sub _train_number_form_profile {#{{{
    my $this = shift;

    return  {
        required=>'train_number',
    };
}#}}}


1;
